package com.xzx.java.kit;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;

/**
 * @author xinzhixuan
 * @version V1.0
 * @date 2017/9/6 17:46
 */
public class SocketKit {

    /**
     * 判断TCP UDP 端口是否可用
     * @param port 端口号
     * @return .
     */
    public static boolean available(int port) {
        if (port <= 0) {
            throw new IllegalArgumentException("Invalid start port: " + port);
        }

        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);
            return true;
        } catch (IOException e) {
            // 端口被占用
        } finally {
            if (ds != null) {
                ds.close();
            }

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    // should not be thrown, just detect port available.
                }
            }
        }
        return false;
    }
}
